package cc.aliza.lib.mongo.core.encoder;

import cc.aliza.lib.mongo.core.InternalDao;
import cc.aliza.lib.mongo.core.annotations.Id;
import cc.aliza.lib.mongo.core.cache.DaoCache;
import cc.aliza.lib.mongo.core.exception.IdException;
import cc.aliza.lib.mongo.core.utils.Operator;
import org.bson.types.ObjectId;

import java.lang.reflect.Field;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public class IdEncoder extends AbstractEncoder {

    private Id id;

    public IdEncoder(Object obj, Field field) {
        super(obj, field);
        id = field.getAnnotation(Id.class);
    }

    @Override
    public boolean isNullField() {
        return false;
    }

    @Override
    public String getFieldName() {
        return Operator.ID;
    }

    @Override
    public Object encode() {
        return fixIdValue();
    }

    private Object fixIdValue() {
        Object result = null;
        switch (id.type()) {
            case AUTO_GENERATE:
                result = value == null ? new ObjectId() : new ObjectId(value.toString());
                break;
            case AUTO_INCREASE:
                if (value == null) {
                    InternalDao dao = DaoCache.getInstance().get(clazz);
                    long max = dao.getMaxId();
                    result = max == 0 ? id.start() : max + 1L;
                } else {
                    result = Long.parseLong(value.toString());
                }
                break;
            case USER_DEFINE:
                if (value == null) {
                    throw new IdException("user-defined id doesn't have value!");
                }
                result = value.toString();
        }
        return result;
    }
}
